package com.njrsrc.android.tasks;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.webkit.WebView;

import com.njrsrc.android.bean.NewsInfo;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class NewsDetailTask extends AsyncTask<Object, Integer, Object> {
	private String url;
	private Handler mHandler;
	private WebView webView;
	private UserInfo userInfo;

	@Override
	protected Object doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		mHandler = (Handler) params[0];
		url = (String) params[1];
		userInfo = (UserInfo) params[2];
		webView = (WebView) params[3];
		JSONObject jsonObject = Helpers.getJSONArrayByGet(url);
		Message msg = mHandler.obtainMessage();
		try {
			if(jsonObject == null)
			{
				msg.what = MsgID.NEWS_DETAIL_QUERY_ERROR;
			}
			else if (jsonObject.toString().contains("error_code")) {
				// 返回错误
				userInfo.setError_code(jsonObject.getString("error_code"));
				userInfo.setError_message(jsonObject.getString("error_message"));
				msg.what = MsgID.NEWS_DETAIL_QUERY_FAIL;
			} else {
				msg.what = MsgID.NEWS_DETAIL_QUERY_SUCCESS;
				NewsInfo newsInfo = new NewsInfo();
				newsInfo.setNews_id(jsonObject.getString("news_id"));
				newsInfo.setTitle(jsonObject.getString("title"));
				newsInfo.setSubtitle(jsonObject.getString("subtitle"));
				newsInfo.setContent(jsonObject.getString("content"));
				return newsInfo;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHandler.sendMessage(msg);
		return null;
	}
	
	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if(result != null)
		{
			NewsInfo newsInfo = (NewsInfo) result;
			webView.getSettings().setDefaultTextEncodingName("utf-8") ;
			try {
				webView.loadData(newsInfo.getContent(),"text/html; charset=UTF-8", null) ;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}